<!-- src/views/student/BatchImportStudent.vue -->
<template>
  <section class="batch-import">
    <h3>📁 批量导入学员</h3>
    <p style="color: #666; margin-bottom: 10px;">
      下载模板，填写后上传 Excel 文件（支持 .xlsx 和 .xls）
    </p>

    <!-- 下载模板按钮 -->
    <el-button type="info" size="small" icon="el-icon-download" @click="downloadTemplate">
      下载导入模板
    </el-button>

    <!-- 文件上传 -->
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :http-request="handleExcelUpload"
      :show-file-list="true"
      :accept="'.xlsx, .xls'"
      :auto-upload="true"
      style="width: 400px; margin: 20px auto;"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将 Excel 文件拖到此处，或 <em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">仅支持 .xlsx 或 .xls 格式</div>
    </el-upload>
  </section>
</template>

<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  name: 'BatchImportStudent',
  methods: {
    // 📥 下载模板：包含必填项说明和自动年份建议
    downloadTemplate() {
      const currentYear = new Date().getFullYear();
      const templateData = [
        ['警号*', '姓名*', '电话号码*', '身份证号*', '单位所在地*', '专业', '年度', '中队'],
        ['', '张三', '13812345678', '360101199003071234', '南昌铁路公安处', '刑侦', currentYear, '一中队'],
        ['', '李四', '13912345678', '360101199104081242', '厦门铁路公安处', '治安', currentYear, '二中队'],
        ['','王五','13712345678','360101199104081243','赣州铁路公安处','','','','']
      ];

      const ws = XLSX.utils.aoa_to_sheet(templateData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '学员信息');

      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([wbout], { type: 'application/octet-stream' });
      saveAs(blob, `学员导入模板_${currentYear}.xlsx`);
    },

    // 📤 处理上传的 Excel 文件
    handleExcelUpload({ file }) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          if (jsonData.length <= 1) {
            this.$message.warning('Excel 文件为空或仅含标题行');
            return;
          }

          const headers = jsonData[0];
          const rows = jsonData.slice(1);

          const currentYear = new Date().getFullYear(); // 自动获取当前年份
          const students = [];
          const errors = []; // 收集解析失败的行号

          rows.forEach((row, index) => {
            const lineNumber = index + 2; // 表格行号（从第2行开始数据）

           const studentId = row[0] !== undefined ? row[0].toString().trim() : '';
            const studentName = row[1] !== undefined ? row[1].toString().trim() : '';
            const tel = row[2] !== undefined ? row[2].toString().trim() : '';
            const cardId = row[3] !== undefined ? row[3].toString().trim() : '';
            const institute = row[4] !== undefined ? row[4].toString().trim() : '';
            const major = row[5] !== undefined ? row[5].toString().trim() : null;
            const grade = row[6] !== undefined ? row[6].toString().trim() : currentYear;
            const clazz = row[7] !== undefined ? row[7].toString().trim() : null;

            // 必填字段校验
            if (!studentId || !studentName || !tel || !cardId || !institute) {
              errors.push(`第 ${lineNumber} 行：警号、姓名、电话、身份证、单位为必填项`);
              return; // 跳过该行
            }

            // 身份证格式校验（可选增强）
            const idRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
            if (!idRegex.test(cardId)) {
              errors.push(`第 ${lineNumber} 行：身份证格式不正确`);
              return;
            }

            // 自动识别性别
            const sex = cardId && cardId.length === 18
              ? (parseInt(cardId.charAt(16), 10) % 2 === 1 ? '男' : '女')
              : null;

            students.push({
              studentId,
              studentName,
              tel,
              cardId,
              institute,
              major,
              grade,
              clazz,
              email: null,
              pwd: '123456',
              role: 2,
              sex
            });
          });

          // 如果有校验错误，提示用户并终止提交
          if (errors.length > 0) {
            this.$alert(errors.join('<br>'), '数据校验未通过', {
              dangerouslyUseHTMLString: true,
              type: 'error',
              showClose: false
            });
            return;
          }

          if (students.length === 0) {
            this.$message.warning('未生成任何有效学员数据');
            return;
          }

          // 提交批量数据
          this.$axios({
            url: '/api/students/batch',
            method: 'post',
            data: students
          })
            .then(res => {
              if (res.data.code === 200) {
               const success = res.data.data && res.data.data.successCount !== undefined 
                ? res.data.data.successCount
                : students.length;

                const fail = res.data.data && res.data.data.failCount !== undefined
                ? res.data.data.failCount 
                : 0;
                this.$message.success(`导入成功 ${success} 条，失败 ${fail} 条`);
              } else {
                this.$message.error(res.data.message || '批量导入失败');
              }
            })
            .catch(() => {
              this.$message.error('网络错误，无法提交数据');
            });

        } catch (error) {
          this.$message.error('解析 Excel 文件失败，请检查文件格式');
          console.error(error);
        }
      };
      reader.readAsArrayBuffer(file);
    }
  }
};
</script>

<style scoped>
.batch-import {
  padding: 20px 40px;
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}
</style>